import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LayoutView from '../views/Layout/LayoutView.vue'

Vue.use(VueRouter)

const routes = [
  {path: '/login', name: 'login', component: () => import('../views/login/Login.vue')},
  {path: '/register', name: 'login', component: () => import('../views/register/Register.vue')},
  {
    path: '/',
    name: 'layout',
    component: LayoutView,
    children:[
      {
        path: '/ecahrt',
        name: 'ecahrt',
        component: () => import('../views/echart/Echart.vue')
      },
      {
        path: '/home',
        name: 'home',
        component:HomeView
      },
      {
        path: '/about',
        name: 'about',
        component: () => import('../views/AboutView.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('../views/user/User.vue')
      },


    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 路由守卫
router.beforeEach((to ,from, next) => {

  if (to.path === '/') {
    return next("/login");
  }
  let user = localStorage.getItem("user");
  if (!user && to.path !== '/login' && to.path !== '/register' && to.path !== '/front/index') {
    return next("/login");
  }
  next();
})

export default router
